package com.web.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.web.entity.Token;
import com.web.mapper.TokenMapper;
import com.web.service.ITokenService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.web.util.LoginException;
import com.web.util.ServiceException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hgjxyz
 * @since 2020-11-18
 */
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token> implements ITokenService {

    @Override
    public String addToken(String id, Integer type) throws ServiceException {
        Token token = this.selectById(id);
        if(token == null){
            token = new Token();
            token.setId(id);
            token.setTheType(type);
            token.setToken(UUID.randomUUID().toString());
            token.setTime(new Date());
            if(!this.insert(token))throw new ServiceException("登陆失败");
            return token.getToken();
        }
        token.setToken(UUID.randomUUID().toString());
        token.setTime(new Date());
        if(!this.updateById(token))throw new ServiceException("登陆失败");
        return token.getToken();
    }

    @Override
    public Token getByToken(String token) throws LoginException {
        Wrapper<Token> wrapper = new EntityWrapper<>();
        wrapper.eq("token", token);
        Token entity = this.selectOne(wrapper);
        if(entity == null || entity.getToken() == null || entity.getToken().equals(""))
            throw new LoginException("请重新登陆");
        entity.setTime(new Date());
        this.updateById(entity);
        return entity;
    }
}
